package com.xbongbong.pro.service.toolbox.subform.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.pojo.dto.PaasConfigGetDTO;
import com.xbongbong.pro.pojo.vo.PaasConfigGetVO;
import com.xbongbong.pro.service.toolbox.subform.PaasConfigService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/03/30 15:55
 */
@Service("paasConfigService")
public class PaasConfigServiceImpl implements PaasConfigService {

    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    @Override
    public PaasConfigGetVO getSubFormConfig(PaasConfigGetDTO paasConfigGetDTO) throws XbbException {
        String corpid = paasConfigGetDTO.getCorpid();

        Integer subFormRowNum = PaasConstant.SUB_FORM_MAX_LARGE;
        Integer selectProductRowNum = PaasConstant.SELECT_PRODUCT_MAX_ROW_LARGE;
        String alias = CompanyConfigEnum.SUB_FORM_ROW_NUM.getAlias();
        String value = paasRedisHelper.getValue(alias, corpid);
        if (StringUtil.isNotEmpty(value)) {
            return JSON.parseObject(value, PaasConfigGetVO.class);
        }
        CompanyConfigEntity subFormRowNumEntity = companyConfigModel.getByConfigAlias(alias, corpid);
        if (Objects.nonNull(subFormRowNumEntity)) {
            JSONObject jsonObject = JSON.parseObject(subFormRowNumEntity.getConfigValue());
            subFormRowNum = jsonObject.getInteger("subFormRowNum");
            selectProductRowNum = jsonObject.getInteger("selectProductRowNum");
        }
        PaasConfigGetVO paasConfigGetVO = new PaasConfigGetVO(subFormRowNum, selectProductRowNum);
        paasRedisHelper.setValue(alias, corpid, paasConfigGetVO, TimeConstant.TEN_MINUTE_DURATION);
        return new PaasConfigGetVO(subFormRowNum, selectProductRowNum);
    }
}
